<?php

class User 
{

	public $oldData;

	public function __construct()
	{
		// 原来的数据取出来
		$oldData = file_get_contents("./db/user.txt");
		// 转化为数组
		$this->oldData = json_decode($oldData,true);
		# code...
	}

	public function add()
	{
		$user = $_POST;

		$user['create_time'] = time();

		$user['password'] = md5($user['password']);

		unset($user['repassword']);

		$this->oldData[] = $user;

		$this->saveData();

		$this->web_ok();
	}

	public function saveData()
	{
		file_put_contents("./db/user.txt",json_encode($this->oldData));
	}

	public function web_ok()
	{
		header("Location:./index.php");
	}
	
	public function register()
	{
		include './template/register.html';
	}

	public function check_phone($data)
	{
		$preg = "/^1\d{10}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('手机格式不正确');
		}

		foreach ($this->oldData as  $row) {
			if($row['phone']==$data){
				$this->error('手机已存在');
			}
		}

		$this->ok('可用');
	}

	public function check_username($data)
	{
		$preg = "/^[a-zA-Z]\w{5,7}$/";

		$c = preg_match($preg,$data);

		if(!$c){

			throw new Exception("不能数字，下划线开头，6-8位", 1);
			// $this->error('不能数字，下划线开头，6-8位');
		}

		foreach ($this->oldData as  $row) {
			if($row['username']==$data){
				throw new Exception("用户名已存在", 1);
				// $this->error('用户名已存在');
			}
		}

		$this->ok('可用');
	}

	public function error($msg)
	{
		exit(json_encode(['error'=>1,'info'=>$msg]));
	}

	public function ok($msg)
	{
		exit(json_encode(['error'=>0,'info'=>$msg]));
	}

	public function check_email($data)
	{
		$preg = "/^\w+@([\da-z]{1,2}|[\da-z][\da-z-]+[\da-z])(\.[a-z]{2,})+$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('邮箱格式不正确');
		}

		foreach ($this->oldData as  $row) {
			if($row['email']==$data){
				$this->error('邮箱已存在');
			}
		}

		$this->ok('可用');
	}
	public function check_password($data)
	{
		$preg = "/^\w{6,16}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('密码长度6-16位');
		}

		$this->ok('可用');
	}

	public function check_repassword($data)
	{
		$preg = "/^\w{6,16}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('密码长度6-16位');
		}

		if($data!=$_POST['password']){
			$this->error('两次密码不一样');
		}

		$this->ok('可用');
	}

	public function register_ajax()
	{

		$name = "check_".$_POST['name'];

		$data = $_POST['data'];

		try{
			$this->$name($data);
		}catch (Exception $e) {
			$this->error($e->getMessage());
		}
	}

	public function login()
	{
		$username = $_POST['username'];

		$password = $_POST['password'];

		foreach ($this->oldData as $row) {
			if($row['username']==$username && $row['password']==md5($password)){
				$_SESSION['user'] = $row;
				$this->ok('登录成功');
			}
		}

		$this->error('用户名或者密码不正确');
	}

	public function loginout()
	{
		session_unset();

		$this->web_ok();
	}

	public function is_login()
	{
		# code...
	}
}